﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using HopNguyenCore;
using HopNguyenCore.Extensions;

namespace HopNguyenCms.Controllers
{
    public class CPanelController : Controller
    {
        private HopNguyenEntities db = new HopNguyenEntities();
        //
        // GET: /CPanel/

        public ActionResult Index()
        {
            if (Session[Admin.CURRENT_ADMIN_SESSION_KEY] == null)
            {
                return View("Login");
            }
            //if (Request.Cookies["_uid"] != null)
            //{
            //    var user = new Admin().Login(Request.Cookies["_uid"]["username"], Request.Cookies["_uid"]["password"]);
            //    if (user != null)
            //    {
            //        return View("Index");
            //    }
            //}

            return View("Index");
        }

        [HttpPost]
        public ActionResult Login(string username, string password, string remember)
        {
            try
            {
                password = MD5.Encrypt(password);
                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                {
                    ViewBag.Error = "The user name or password incorrect.";
                    return View("Login");
                }
                var user = new Admin().Login(username, password);
                if (!user)
                {
                    ViewBag.Error = "The username or password is incorrect.";
                    return View("Login");
                }
                //if (remember == "on")
                //{
                //    Response.Cookies["_uid"]["username"] = username;
                //    Response.Cookies["_uid"]["password"] = password;
                //    Response.Cookies["_uid"].Expires = DateTime.Now.AddYears(1);
                //}
                return Redirect("/cpanel");
            }
            catch (Exception ex)
            {
                SystemLog.WriteLog(ex);
                throw;
            }

        }
        public ActionResult Logout()
        {
            Session[Admin.CURRENT_ADMIN_SESSION_KEY] = null;
            Admin.Current = null;
            return View("Login");
        }

        #region System logs
        public ActionResult SystemLogs()
        {
            var systemlogs = db.SystemLogs.Include(s => s.Admin);
            return View(systemlogs.ToList());
        }

        #endregion
    }
}
